package com.junzhiit.nengji.cms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.serializer.Format;
import com.junzhiit.nengji.bo.AnalysisReportBO;
import com.junzhiit.nengji.bo.GoodsAnalysisBO;
import com.junzhiit.nengji.bo.GoodsAnalysisInfoBO;
import com.junzhiit.nengji.bo.GoodsBO;
import com.junzhiit.nengji.bo.GoodsListBO;
import com.junzhiit.nengji.bo.OrdersAndDetailsBO;
import com.junzhiit.nengji.bo.OrdersAndGoodsBO;
import com.junzhiit.nengji.bo.PayHistoryBO;
import com.junzhiit.nengji.bo.ShopAnalysisBO;
import com.junzhiit.nengji.bo.TransactionAnalysisBO;
import com.junzhiit.nengji.cms.service.ReportService;
import com.junzhiit.nengji.cms.web.exception.ChainNotFoundException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.exception.UserNotFoundException;
import com.junzhiit.nengji.cms.web.util.Constants;
import com.junzhiit.nengji.cms.web.util.FileUtil;
import com.junzhiit.nengji.cms.web.util.excel.GenerateWorkbook;
import com.junzhiit.nengji.cms.web.util.excel.ViewExcel;
import com.junzhiit.nengji.cms.web.util.excel.enums.WorkbookType;
import com.junzhiit.nengji.cms.web.vo.AnalysisReportVO;
import com.junzhiit.nengji.cms.web.vo.GoodsAnalysisInfoVO;
import com.junzhiit.nengji.cms.web.vo.GoodsAnalysisVO;
import com.junzhiit.nengji.cms.web.vo.GoodsListVO;
import com.junzhiit.nengji.cms.web.vo.OrdersAndDetailsVO;
import com.junzhiit.nengji.cms.web.vo.OrdersAndGoodsVO;
import com.junzhiit.nengji.cms.web.vo.PayHistoryVO;
import com.junzhiit.nengji.cms.web.vo.ShopAnalysisVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.cms.web.vo.TransactionAnalysisVO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.GoodsHistoryDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersDataHistoryDAO;
import com.junzhiit.nengji.dao.PayHistoryDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.ShopHistoryDAO;
import com.junzhiit.nengji.dao.TransactionDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.enums.AnalysisType;
import com.junzhiit.nengji.model.enums.CouponsType;
import com.junzhiit.nengji.model.enums.ExportType;
import com.junzhiit.nengji.model.enums.GoodsStatus;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.LoginType;
import com.junzhiit.nengji.model.enums.OrderGoodsStatus;
import com.junzhiit.nengji.model.enums.OrderStatus;
import com.junzhiit.nengji.model.enums.OrderType;
import com.junzhiit.nengji.model.enums.PayWay;

@Service
public class ReportServiceImpl extends BaseServiceImpl implements ReportService {

	@Autowired
	private TransactionDAO transactionDAO;

	@Autowired
	private GoodsHistoryDAO goodsHistoryDAO;

	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;

	@Autowired
	private PayHistoryDAO payHistoryDAO;

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private ShopDAO shopDAO;

	@Autowired
	private OrdersDAO ordersDAO;

	@Autowired
	private ChainDAO chainDAO;

	 @Autowired
	 private OrdersDataHistoryDAO ordersDataHistoryDAO;

	@Autowired
	private ShopHistoryDAO shopHistoryDAO;

	@Value("${upload.report.statistical}")
	private String transactionStatisticalPath;

	@Value("${upload.report.transaction}")
	private String transactionPath;

	@Value("${upload.report.goods}")
	private String goodsHistoryPath;

	@Value("${upload.report.shop}")
	private String shopHistoryPath;

	@Value("${upload.report.record}")
	private String consumeRecordPath;

	@Value("${upload.report.ranking}")
	private String consumeRankingPath;

	@Value("${upload.report.user.consume}")
	private String userConsumePath;
	
	@Value("${upload.report.orders}")
	private String ordersPath;
	
	@Value("${upload.report.orders.history}")
	private String ordersDataPath;
	
	@Override
	public void exportTransactionAnalysisAllExcel(HttpServletResponse response, HttpServletRequest request,
			String sessionId, Integer analysisType, String date, String startTime, String endTime) {
		String key = DIYKey.getSessionHashKey(sessionId);
		String shopId = null;
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			shopId = session.getSystemId();
		}

		String dateStr = null;
		if (analysisType == AnalysisType.DAY.toIntValue()) {
			dateStr = date;
		} else if (analysisType == AnalysisType.MONTH.toIntValue()) {
			int year = DateUtil.getYear(DateUtil.parseDate(date));
			int month = DateUtil.getMonth(DateUtil.parseDate(date)) + 1;

			dateStr = year + DateUtil.DATE_DIVISION;
			if (month < 10) {
				dateStr += "0";
			}
			dateStr += month;
		}

		TransactionAnalysisVO analysisVO = new TransactionAnalysisVO();
		TransactionAnalysisBO bo = null;

		if (analysisType == AnalysisType.DAY.toIntValue() || analysisType == AnalysisType.MONTH.toIntValue()) {
			bo = transactionDAO.getTransactionAnalysis(shopId, analysisType, dateStr);

			analysisVO.setSevenRepeatPurchase((bo.getSevenRepeatPurchase() == null) ? 0 : bo.getSevenRepeatPurchase());
			analysisVO
					.setThirtyRepeatPurchase((bo.getThirtyRepeatPurchase() == null) ? 0 : bo.getThirtyRepeatPurchase());
			analysisVO
					.setNinetyRepeatPurchase((bo.getNinetyRepeatPurchase() == null) ? 0 : bo.getNinetyRepeatPurchase());

		} else if (analysisType == AnalysisType.CUSTOM.toIntValue()) {
			bo = transactionDAO.getTransactionAnalysis(shopId, DateUtil.getDateStart(DateUtil.parseDate(startTime)),
					DateUtil.getDateEnd(DateUtil.parseDate(endTime)));
		}

		analysisVO.setClientPrice(bo.getClientPrice() == null ? 0.00 : Format.decimal(bo.getClientPrice()));
		analysisVO.setOrdersMoney(bo.getOrdersMoney() == null ? 0.00 : Format.decimal(bo.getOrdersMoney()));
		analysisVO.setPayMoney(bo.getPayMoney() == null ? 0.00 : Format.decimal(bo.getPayMoney()));
		analysisVO.setOrdersCount(bo.getOrdersCount() == null ? 0 : bo.getOrdersCount());
		analysisVO.setOrdersUserCount(bo.getOrdersUserCount() == null ? 0 : bo.getOrdersUserCount());
		analysisVO.setPayNumber(bo.getPayNumber() == null ? 0 : bo.getPayNumber());
		analysisVO.setPayOrdersCount(bo.getPayOrdersCount() == null ? 0 : bo.getPayOrdersCount());
		analysisVO.setPayUserCount(bo.getPayUserCount() == null ? 0 : bo.getPayUserCount());
		analysisVO.setOrdersGoodsCount((bo.getOrdersGoodsCount() == null) ? 0 : bo.getOrdersGoodsCount());
		analysisVO.setPaySuccess((bo.getPaySuccess() == null) ? 0.00 : Format.decimal(bo.getPaySuccess() * 100));

		List<TransactionAnalysisVO> list = new ArrayList<TransactionAnalysisVO>();
		list.add(analysisVO);

		String fileName = Constants.TRANSACTION_ANALYSIS_STATISTICAL_REPORT_NAME
				+ DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve = new ViewExcel();
		HSSFWorkbook workbook = GenerateWorkbook.transactionAnalysisStatisticalReport(list, analysisType);
		String fileFullPath = ve.saveExcelDocument(workbook, transactionStatisticalPath, fileName, request,
				WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);

	}

	@Override
	public void exportTransactionAnalysisExcel(HttpServletResponse response, HttpServletRequest request,
			String sessionId, Integer exportType) {
		String key = DIYKey.getSessionHashKey(sessionId);
		String shopId = null;
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			shopId = session.getSystemId();
		}

		int days = 1;
		if (exportType == ExportType.WEEK.toIntValue()) {
			days = 7;
		} else if (exportType == ExportType.MONTH.toIntValue()) {
			days = 30;
		}

		List<TransactionAnalysisBO> list = transactionDAO.findAll(shopId, days);
		for (TransactionAnalysisBO bo : list) {
			bo.setOrdersMoney(bo.getOrdersMoney() == null ? 0.00 : Format.decimal(bo.getOrdersMoney()));
			bo.setPayMoney(bo.getPayMoney() == null ? 0.00 : Format.decimal(bo.getPayMoney()));
			bo.setOrdersCount(bo.getOrdersCount() == null ? 0 : bo.getOrdersCount());
			bo.setOrdersUserCount(bo.getOrdersUserCount() == null ? 0 : bo.getOrdersUserCount());
			bo.setPayNumber(bo.getPayNumber() == null ? 0 : bo.getPayNumber());
			bo.setPayOrdersCount(bo.getPayOrdersCount() == null ? 0 : bo.getPayOrdersCount());
			bo.setPayUserCount(bo.getPayUserCount() == null ? 0 : bo.getPayUserCount());
			bo.setOrdersGoodsCount((bo.getOrdersGoodsCount() == null) ? 0 : bo.getOrdersGoodsCount());
		}

		String fileName = Constants.TRANSACTION_ANALYSIS_REPORT_NAME
				+ DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve = new ViewExcel();
		HSSFWorkbook workbook = GenerateWorkbook.transactionAnalysisReport(list);
		String fileFullPath = ve.saveExcelDocument(workbook, transactionPath, fileName, request,
				WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);
	}

	@Override
	public void exportConsumeRecordExcel(HttpServletResponse response, HttpServletRequest request, String sessionId,
			PayHistoryVO payHistoryVO) {
		String key = DIYKey.getSessionHashKey(sessionId);
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		String systemId=session.getSystemId();
		Shop shop=shopDAO.query(systemId);
		Chain chain=chainDAO.query(systemId);
		if(shop==null&&chain==null){
			throw new ShopNotFoundException("店铺/品牌不存在");
		}
		PayHistoryBO payHistoryBO = new PayHistoryBO();
		BeanUtils.copyProperties(payHistoryVO, payHistoryBO);
		if(shop!=null){
			payHistoryBO.setShopId(systemId);
		}
		if(chain!=null){
			payHistoryBO.setChainId(systemId);
		}
		payHistoryBO.setStartTime(DateUtil.getDateStart(DateUtil.parseDate(payHistoryVO.getStartTime())));
		payHistoryBO.setEndTime(DateUtil.getDateEnd(DateUtil.parseDate(payHistoryVO.getEndTime())));
		List<PayHistoryBO> list = payHistoryDAO.queryPayHistory(payHistoryBO, null, null);
		for (int i = 0; i < list.size(); i++) {
			Integer way = list.get(i).getWay();
			if (way == PayWay.WECHAT.toIntValue()) {
				list.get(i).setPayWay(PayWay.WECHAT.toStringText());
			} else if (way == PayWay.CASH.toIntValue()) {
				list.get(i).setPayWay(PayWay.CASH.toStringText());
			} else if (way == PayWay.REDEEM.toIntValue()) {
				list.get(i).setPayWay(PayWay.REDEEM.toStringText());
			}
		}
		String fileName = Constants.CONSUME_RECORD_REPORT_NAME
				+ DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve = new ViewExcel();
		HSSFWorkbook workbook = GenerateWorkbook.consumeRecordReport(list);
		String fileFullPath = ve.saveExcelDocument(workbook, consumeRecordPath, fileName, request,
				WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);
	}

	@Override
	public void exportConsumeRankingExcel(HttpServletResponse response, HttpServletRequest request, String sessionId,PayHistoryVO payHistoryVO) {
		SystemUserSessionVO session=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		PayHistoryBO phb=new PayHistoryBO();
		BeanUtils.copyProperties(payHistoryVO, phb);
		phb.setStartTime(DateUtil.parseDate(payHistoryVO.getStartTime()));
		phb.setEndTime(DateUtil.parseDate(payHistoryVO.getEndTime()));
		if(LoginType.SHOP.toIntType()==session.getLoginType()){
			phb.setShopId(session.getSystemId());
		} 
		List<PayHistoryBO> phbList=payHistoryDAO.queryPayRanking(phb,null,null);
		String fileName=Constants.CONSUME_RANKING_REPORT_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve=new ViewExcel();
		HSSFWorkbook workbook=GenerateWorkbook.consumeRankingReport(phbList);
		String fileFullPath=ve.saveExcelDocument(workbook, consumeRankingPath, fileName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);
	}

	@Override
	public void exportUserConsumeExcel(HttpServletResponse response, HttpServletRequest request, String sessionId,
			String userId) {
		String key = DIYKey.getSessionHashKey(sessionId);
		String shopId = null;
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			shopId = session.getSystemId();
		}
		if (userDAO.findUserId(userId) == null) {
			throw new UserNotFoundException("该用户不存在");
		}
		List<PayHistoryBO> list = payHistoryDAO.queryUserPayHistory(shopId, userId, null, null);
		for (int i = 0; i < list.size(); i++) {
			Integer way = list.get(i).getWay();
			if (way == PayWay.WECHAT.toIntValue()) {
				list.get(i).setPayWay(PayWay.WECHAT.toStringText());
			}  else if (way == PayWay.CASH.toIntValue()) {
				list.get(i).setPayWay(PayWay.CASH.toStringText());
			} else if (way == PayWay.REDEEM.toIntValue()) {
				list.get(i).setPayWay(PayWay.REDEEM.toStringText());
			}
		}

		String fileName = Constants.USER_CONSUME_RECORD_REPORT_NAME
				+ DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve = new ViewExcel();
		HSSFWorkbook workbook = GenerateWorkbook.consumeRecordReport(list);
		String fileFullPath = ve.saveExcelDocument(workbook, userConsumePath, fileName, request,
				WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);
	}

	 @Override
	 public void exportDataReportExcel(HttpServletResponse response,HttpServletRequest request,OrdersAndGoodsVO ordersAndGoodsVO) {
		 OrdersAndGoodsBO ordersAndGoodsBO=new OrdersAndGoodsBO();
		 ordersAndGoodsBO.setStartTime(ordersAndGoodsVO.getStart());
		 ordersAndGoodsBO.setEndTime(ordersAndGoodsVO.getEnd());
		 if(StringUtils.isNotBlank(ordersAndGoodsVO.getShopsId())){
			 ordersAndGoodsBO.setShopId(ordersAndGoodsVO.getShopsId());
		 }
		 List<OrdersAndGoodsBO> lists =ordersDataHistoryDAO.findDataDatail(ordersAndGoodsBO);
		 for(OrdersAndGoodsBO list:lists){
			 if(list.getPayWay()!=null){
				 list.setPayWayShow(PayWay.toValue(list.getPayWay()).toStringText());
			 }
			 if(StringUtils.isBlank(list.getCouponsName())){
				 list.setCouponsName("无使用优惠券");
				 list.setCouponsTypeName("暂无");
			 }else{
				 if(list.getCouponsType() == CouponsType.PLATFORM.toIntValue()){
					 list.setCouponsTypeName("平台优惠券");
				 }
				 if(list.getCouponsType() == CouponsType.SHOP.toIntValue()){
					 list.setCouponsTypeName("商家优惠券");
				 }
			 }
			 if(StringUtils.isBlank(list.getSkuContentName())){
				 list.setSkuContentName("未开启SKU");
			 }
			 if(list.getIsOpenRebate() == Is.NO.toIntValue()){
				 list.setIsOpen("不返利");
			 }
			 if(list.getIsOpenRebate() == Is.YES.toIntValue()){
				 list.setIsOpen("返利");
			 }
			 if(StringUtils.isBlank(list.getPrimaryBenefitName())){
				 list.setPrimaryBenefitName("无一级分润");
			 }
			 if(StringUtils.isBlank(list.getSecondBenefitName())){
				 list.setSecondBenefitName("无二级分润");
			 }
			 if(list.getReferrerIdentity() == 0){
				 list.setIdentityName("用户");
			 }
			 if(list.getReferrerIdentity() == 1){
				 list.setIdentityName("商家");
			 }
			 if(StringUtils.isBlank(list.getReferrerName())){
				 list.setReferrerName("暂无推荐人");
			 }
			 list.setOrdersGoodsId(list.getOrdersDataHistoryId());
		 }
		 String fileName=Constants.FINANCIAL_STAEMENT+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		 ViewExcel ve=new ViewExcel();
		 HSSFWorkbook workbook=GenerateWorkbook.dataHistoryAnalysisReport(lists);
		 String fileFullPath=ve.saveExcelDocument(workbook, ordersDataPath,
				 fileName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		 FileUtil.download(request, response, fileFullPath);
	 }

	@Override
	public void exportOrdersAndDetailsExcel(HttpServletResponse response, HttpServletRequest request,
			OrdersAndDetailsVO oadv) {
		OrdersAndDetailsBO oadb = new OrdersAndDetailsBO();
		BeanUtils.copyProperties(oadv, oadb);

		if (StringUtils.isBlank(oadv.getShopId())) {
			SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
					.getHash(DIYKey.getSessionHashKey(oadv.getSessionId()), SystemUserSessionVO.class);
			String systemId = systemUserSessionVO.getSystemId();
			if (StringUtils.isNotBlank(systemId)) {
				Shop shop = shopDAO.query(systemId);
				Chain chain = chainDAO.query(systemId);
				if (shop == null && chain == null) {
					throw new ChainNotFoundException("商户/品牌不存在");
				}
				if (shop != null) {// 商户
					oadb.setShopId(shop.getId());
				}
				if (chain != null) {
					oadb.setChainId(chain.getId());
				}
			}
		}

		List<OrdersAndDetailsBO> oadbList = ordersDAO.findOdersAndDetails(oadb);
		for (OrdersAndDetailsBO oadbo : oadbList) {
			oadbo.setPayWayShow(PayWay.toValue(oadbo.getPayWay()).toStringText());
			oadbo.setTypeShow(OrderType.toType(oadbo.getType()).toStringText());
			oadbo.setStatusShow(OrderStatus.toStatus(oadbo.getStatus()).toStringText());
			oadbo.setOrdersGoodsStatusShow(OrderGoodsStatus.toStatus(oadbo.getOrdersGoodsStatus()).toStringText());
			if (oadbo.getType() == OrderType.MAIL.toIntValue()) {
				oadbo.setDistribution("物流派送");
				continue;
			}
			if (oadbo.getType() == OrderType.DELIVERY.toIntValue()) {
				oadbo.setDistribution("外卖配送");
				continue;
			}
			oadbo.setDistribution("暂无");
		}
		String fileName = Constants.ORDERS_DEATAIL
				+ DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve = new ViewExcel();
		HSSFWorkbook workbook = GenerateWorkbook.ordersAndDetailsReport(oadbList, oadv.getType());
		String fileFullPath = ve.saveExcelDocument(workbook, ordersPath, fileName, request,
				WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);
	}

	@Override
	public void exportShopGoodsListExcel(HttpServletResponse response, HttpServletRequest request,GoodsListVO glv) {
		GoodsListBO glb=new GoodsListBO();
		BeanUtils.copyProperties(glv, glb);
		List<GoodsBO> goodsList=shopDAO.findGoodsListByShopId(glb,null,null);
		for(GoodsBO gb:goodsList){
			if(gb.getIsOpenSku()==Is.NO.toIntValue()){
				gb.setIsOpenSkuShow("未开启");
			}
			if(gb.getIsOpenSku()==Is.YES.toIntValue()){
				gb.setIsOpenSkuShow("已开启");
			}
			if(gb.getIsRecommend()==Is.NO.toIntValue()){
				gb.setIsRecommendShow("未推荐");
			}
			if(gb.getIsRecommend()==Is.YES.toIntValue()){
				gb.setIsRecommendShow("已推荐");
			}
			if(gb.getIsOpenRebate()==Is.NO.toIntValue()){
				gb.setIsOpenRebateShow("未开启");
			}
			if(gb.getIsOpenRebate()==Is.YES.toIntValue()){
				gb.setIsOpenRebateShow("已开启");
			}
			if(gb.getStatus()==GoodsStatus.INACTIVE.toIntStatus()){
				gb.setStatusShow("下架");
			}
			if(gb.getStatus()==GoodsStatus.ACTIVE.toIntStatus()){
				gb.setStatusShow("上架");
			}
			if(gb.getStatus()==GoodsStatus.AUDIT.toIntStatus()){
				gb.setStatusShow("待审核");
			}
			if(gb.getStatus()==GoodsStatus.AUDITFAIL.toIntStatus()){
				gb.setStatusShow("审核不通过");
			}
			if(gb.getStatus()==GoodsStatus.AUDITSUCCESS.toIntStatus()){
				gb.setStatusShow("审核通过");
			}
		}
		String fileName=Constants.SHOP_GOODS_LIST_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve=new ViewExcel();
		HSSFWorkbook workbook=GenerateWorkbook.shopGoodsListReport(goodsList);
		String fileFullPath=ve.saveExcelDocument(workbook, shopHistoryPath, fileName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, fileFullPath);
	}

	@Override
	public void exportChainTransactionAnalysis(HttpServletResponse response, HttpServletRequest request,AnalysisReportVO arv) {
		String sessionId=arv.getSessionId();
		SystemUserSessionVO sessionVO=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		String chainId=sessionVO.getSystemId();
		Chain chain=chainDAO.query(chainId);
		if(chain==null){
			throw new ChainNotFoundException("品牌不存在");
		}
		AnalysisReportBO arb=new AnalysisReportBO();
		BeanUtils.copyProperties(arv, arb);
		String currentDate=null;
		if(arb.getAnalysisType()==AnalysisType.DAY.toIntValue()){
			currentDate=arb.getDate();
		}
		if(arb.getAnalysisType()==AnalysisType.MONTH.toIntValue()){
			Integer year=DateUtil.getYear(DateUtil.parseDate(arb.getDate()));
			Integer month=DateUtil.getMonth(DateUtil.parseDate(arb.getDate()))+1;
			currentDate=year+DateUtil.DATE_DIVISION;
			if(month<10){
				currentDate+="0";
			}
			currentDate+=month;
		}
		TransactionAnalysisBO tab=transactionDAO.getChainTransactionAnalysis(arb.getShopId(),DateUtil.getDateStart(DateUtil.parseDate(arb.getStartTime())),DateUtil.getDateEnd(DateUtil.parseDate(arb.getEndTime())), chainId, currentDate, arb.getAnalysisType());
		TransactionAnalysisVO tav=new TransactionAnalysisVO();
		BeanUtils.copyProperties(tab, tav);
		tav.setOrdersGoodsCount(tav.getOrdersGoodsCount()==null?0:tav.getOrdersGoodsCount());;
		tav.setOrdersMoney(tav.getOrdersMoney()==null?0:tav.getOrdersMoney());
		tav.setPayMoney(tav.getPayMoney()==null?0:tav.getPayMoney());
		tav.setPayNumber(tav.getPayNumber()==null?0:tav.getPayNumber());
		tav.setOrdersConversion(tav.getOrdersConversion()==null?0:tav.getOrdersConversion());
		tav.setPayConversion(tav.getPayConversion()==null?0:tav.getPayConversion());
		tav.setPaySuccess(tav.getPaySuccess()==null?0:tav.getPaySuccess());
		tav.setClientPrice(tav.getClientPrice()==null?0:tav.getClientPrice());
		tav.setSevenRepeatPurchase(tav.getSevenRepeatPurchase()==null?0:tav.getSevenRepeatPurchase());
		tav.setThirtyRepeatPurchase(tav.getThirtyRepeatPurchase()==null?0:tav.getThirtyRepeatPurchase());
		tav.setNinetyRepeatPurchase(tav.getNinetyRepeatPurchase()==null?0:tav.getNinetyRepeatPurchase());
		List<TransactionAnalysisVO> tabList=new ArrayList<>();
		tabList.add(tav);
		HSSFWorkbook hwb=GenerateWorkbook.chainTransactionAnalysisReport(tabList);
		ViewExcel ve=new ViewExcel();
		String fileName=Constants.CHAIN_HISTORY_ANALYSIS_REPORT_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		String fileFullPath=ve.saveExcelDocument(hwb, transactionPath, fileName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response,fileFullPath);
	}

	@Override  
	public void exportChainTransactionAnalysisList(HttpServletResponse response, HttpServletRequest request,String sessionId, Integer exportType, String shopId) {
		SystemUserSessionVO sessionVO=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		String chainId=sessionVO.getSystemId();
		Chain chain=chainDAO.query(chainId);
		if(chain==null){
			throw new ChainNotFoundException("品牌不存在");
		}
		Integer days=null;
		if(exportType==ExportType.WEEK.toIntValue()){
			days=7;
		}
		if(exportType==ExportType.MONTH.toIntValue()){
			days=30;
		}
		List<TransactionAnalysisBO> tabList=transactionDAO.getChainTransactionAnalysisList(shopId, chainId, days);
		List<TransactionAnalysisVO> tavList=new ArrayList<>();
		for(TransactionAnalysisBO tab:tabList){
			TransactionAnalysisVO tav=new TransactionAnalysisVO();
			BeanUtils.copyProperties(tab, tav);
			tav.setOrdersGoodsCount(tav.getOrdersGoodsCount()==null?0:tav.getOrdersGoodsCount());;
			tav.setOrdersMoney(tav.getOrdersMoney()==null?0:tav.getOrdersMoney());
			tav.setPayMoney(tav.getPayMoney()==null?0:tav.getPayMoney());
			tav.setPayNumber(tav.getPayNumber()==null?0:tav.getPayNumber());
			tav.setOrdersConversion(tav.getOrdersConversion()==null?0:tav.getOrdersConversion());
			tav.setPayConversion(tav.getPayConversion()==null?0:tav.getPayConversion());
			tav.setPaySuccess(tav.getPaySuccess()==null?0:tav.getPaySuccess());
			tav.setClientPrice(tav.getClientPrice()==null?0:tav.getClientPrice());
			tav.setSevenRepeatPurchase(tav.getSevenRepeatPurchase()==null?0:tav.getSevenRepeatPurchase());
			tav.setThirtyRepeatPurchase(tav.getThirtyRepeatPurchase()==null?0:tav.getThirtyRepeatPurchase());
			tav.setNinetyRepeatPurchase(tav.getNinetyRepeatPurchase()==null?0:tav.getNinetyRepeatPurchase());
			tav.setPayOrdersCount(tav.getPayOrdersCount()==null?0:tav.getPayOrdersCount());
			tav.setPayUserCount(tav.getPayUserCount()==null?0:tav.getPayUserCount());
			tavList.add(tav);
		}
		HSSFWorkbook hwb=GenerateWorkbook.chainTransactionAnalysisListReport(tavList);
		String fullName=Constants.TRANSACTION_ANALYSIS_REPORT_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve=new ViewExcel();
		String filefullPath=ve.saveExcelDocument(hwb, transactionPath, fullName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, filefullPath);
	}

	@Override
	public void exportGoodsAnalysisExcel(HttpServletResponse response, HttpServletRequest request, String sessionId,
			String startTime, String endTime, String shopId) {
		SystemUserSessionVO sessionVO=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		String systemId=sessionVO.getSystemId();
		Integer type=0;
		if(sessionVO.getIsChain()==Is.NO.toIntValue()){
			Shop shop=shopDAO.query(systemId);
			if(shop==null){
				throw new ShopNotFoundException("店铺不存在");
			}
			type=1;
		}
		if(sessionVO.getIsChain()==Is.YES.toIntValue()){
			Chain chain=chainDAO.query(systemId);
			if(chain==null){
				throw new ChainNotFoundException("品牌不存在");
			}
			if(StringUtils.isNoneBlank(shopId)){
				type=1;
				systemId=shopId;
			}	
		}
		Date sTime=DateUtil.getDateStart(DateUtil.parseDate(startTime));
		Date eTime=DateUtil.getDateEnd(DateUtil.parseDate(endTime));
		GoodsAnalysisBO gab=goodsHistoryDAO.getGoodsAnalysis(sTime, eTime, systemId,type);
		GoodsAnalysisVO gav=new GoodsAnalysisVO();
		BeanUtils.copyProperties(gab, gav);
		gav.setGoodsRate(gav.getGoodsRate() == null ? 0.00 : Format.decimal(gav.getGoodsRate() * 100));
		gav.setGoodsViewNumber(gav.getGoodsViewNumber() == null ? 0 : gav.getGoodsViewNumber());
		gav.setVisitUserCount(gav.getVisitUserCount() == null ? 0 : gav.getVisitUserCount());
		gav.setExposureNumber(gav.getExposureNumber() == null ? 0 : gav.getExposureNumber());
		gav.setCartNumber(gav.getCartNumber() == null ? 0 : gav.getCartNumber());
		List<GoodsAnalysisVO> gavList=new ArrayList<>();
		gavList.add(gav);
		HSSFWorkbook hwb=GenerateWorkbook.goodsHistoryAnalysisReport(gavList);
		ViewExcel ve=new ViewExcel();
		String fullName=Constants.GOODS_HISTORY_ANALYSIS_REPORT_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		String filefullPath=ve.saveExcelDocument(hwb, goodsHistoryPath, fullName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, filefullPath);
	}

	@Override
	public void exportAllGoodsAnalysisExcel(HttpServletResponse response, HttpServletRequest request, String sessionId,
			String startTime, String endTime, String shopId) {
		SystemUserSessionVO sessionVO=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		String systemId=sessionVO.getSystemId();
		Integer type=0;
		if(sessionVO.getIsChain()==Is.NO.toIntValue()){
			Shop shop=shopDAO.query(systemId);
			if(shop==null){
				throw new ShopNotFoundException("店铺不存在");
			}
			type=1;
		}
		if(sessionVO.getIsChain()==Is.YES.toIntValue()){
			Chain chain=chainDAO.query(systemId);
			if(chain==null){
				throw new ChainNotFoundException("品牌不存在");
			}
			if(StringUtils.isNoneBlank(shopId)){
				type=1;
				systemId=shopId;
			}	
		}
		Date sTime=DateUtil.getDateStart(DateUtil.parseDate(startTime));
		Date eTime=DateUtil.getDateEnd(DateUtil.parseDate(endTime));
		List<GoodsAnalysisInfoBO> gaibList=goodsHistoryDAO.getAllGoodsAnalysis(null,null,sTime,eTime,systemId,type);
		List<GoodsAnalysisInfoVO> gaivList=new ArrayList<>();
		for(GoodsAnalysisInfoBO gaib:gaibList){
			GoodsAnalysisInfoVO gaiv=new GoodsAnalysisInfoVO();
			BeanUtils.copyProperties(gaib, gaiv);
			gaiv.setGoodsExposureNumber(gaiv.getGoodsExposureNumber() == null ? 0 : gaiv.getGoodsExposureNumber());
			gaiv.setPayUserCount(gaiv.getPayUserCount() == null ? 0 : gaiv.getPayUserCount());
			gaiv.setPayGoodsNumber(gaiv.getPayGoodsNumber() == null ? 0 : gaiv.getPayGoodsNumber());
			gaiv.setOrdersUserCount(gaiv.getOrdersUserCount() == null ? 0 : gaiv.getOrdersUserCount());
			gaiv.setOrdersGoodsNumber(gaiv.getOrdersGoodsNumber() == null ? 0 : gaiv.getOrdersGoodsNumber());
			gaiv.setVisitUserCount(gaiv.getVisitUserCount() == null ? 0 : gaiv.getVisitUserCount());
			gaiv.setGoodsViewNumber(gaiv.getGoodsViewNumber() == null ? 0 : gaiv.getGoodsViewNumber());
			gaiv.setGoodsCollections(gaiv.getGoodsCollections() == null ? 0 : gaiv.getGoodsCollections());
			gaiv.setCartGoodsNumber(gaiv.getCartGoodsNumber() == null ? 0 : gaiv.getCartGoodsNumber());
			gaiv.setSingleRate(gaiv.getSingleRate() == null ? 0.00: Format.decimal(gaiv.getSingleRate() * 100));
			gaivList.add(gaiv);
		}
		HSSFWorkbook hwb=GenerateWorkbook.goodsHistoryInfoAnalysisReport(gaivList);
		ViewExcel ve=new ViewExcel();
		String fullName=Constants.GOODS_HISTORY_ONFO_ANALYSIS_REPORT_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		String filefullPath=ve.saveExcelDocument(hwb, goodsHistoryPath, fullName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, filefullPath);
	}

	@Override
	public void exportShopAnalysisExcel(HttpServletResponse response, HttpServletRequest request, String sessionId,
			String startTime, String endTime, String shopId) {
		SystemUserSessionVO sessionVO=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		String systemId=sessionVO.getSystemId();
		Integer type=0;
		if(sessionVO.getIsChain()==Is.NO.toIntValue()){
			Shop shop=shopDAO.query(systemId);
			if(shop==null){
				throw new ShopNotFoundException("店铺不存在");
			}
			type=1;
		}
		if(sessionVO.getIsChain()==Is.YES.toIntValue()){
			Chain chain=chainDAO.query(systemId);
			if(chain==null){
				throw new ChainNotFoundException("品牌不存在");
			}
			if(StringUtils.isNoneBlank(shopId)){
				type=1;
				systemId=shopId;
			}	
		}
		Date sTime=DateUtil.getDateStart(DateUtil.parseDate(startTime));
		Date eTime=DateUtil.getDateEnd(DateUtil.parseDate(endTime));
		ShopAnalysisBO sab=shopHistoryDAO.getShopAnalysis(sTime, eTime, systemId, type);		
		ShopAnalysisVO sav=new ShopAnalysisVO();
		BeanUtils.copyProperties(sab, sav);
		sav.setShopViewNumber(sav.getShopViewNumber()==null?0:sav.getShopViewNumber());
		sav.setShopShareNumber(sav.getShopShareNumber()==null?0:sav.getShopShareNumber());
		List<ShopAnalysisVO> savList=new ArrayList<>();
		savList.add(sav);
		HSSFWorkbook hwb=GenerateWorkbook.shopHistoryAnalysisReport(savList);
		String fullName=Constants.SHOP_HISTORY_ANALYSIS_REPORT_NAME+DateUtil.getCurrentDateStr(DateUtil.DATE_PATTERN_YYYYMMDD);
		ViewExcel ve=new ViewExcel();
		String filefullPath=ve.saveExcelDocument(hwb, shopHistoryPath, fullName, request, WorkbookType.HSSFWORKBOOK.toIntValue());
		FileUtil.download(request, response, filefullPath);
	}
}
